package com.ocean4.upload;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

import com.ocean4.socialmap.MainActivity;
import com.ocean4.socialmap.R;

@TargetApi(Build.VERSION_CODES.KITKAT) public class ChooseImages extends ActionBarActivity{

	ImageButton imageBtnImage;
	Button btnCapture, btnUpload;
	
	int SELECT_FILE_1 = 0;
	int CAPTURE_IMAGE = 1;
	
	String selectedPath1, selectedPath2;
    Uri imageUri                      = null;
    Bitmap bitmap = null;
    
    ProgressDialog dialog = null;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.upload_image_screen);
		
		btnCapture = (Button) findViewById(R.id.btnCaptureImage);
		btnUpload = (Button) findViewById(R.id.button1);
		imageBtnImage = (ImageButton) findViewById(R.id.imageBtnImage);
		
		imageBtnImage.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				openGallery(SELECT_FILE_1);
			}
		});
		btnUpload.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Thread(new Runnable() {
                    public void run() {
						uploadFile("/storage/sdcard/Android/data/com.android.browser/files/Download/2014-10-05-09-46-54-1616741489.jpeg");
						
						
					}
				}).start();
				
				
			}
		});
		
		btnCapture.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
/*************************** Camera Intent Start ************************/  
                
                // Define the file-name to save photo taken by Camera activity
                
                String fileName = "Camera_Example.jpg";
                
                // Create parameters for Intent with filename
                
                ContentValues values = new ContentValues();
                
                values.put(MediaStore.Images.Media.TITLE, fileName);
                
                values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
                
                // imageUri is the current activity attribute, define and save it for later usage  
                
                imageUri = getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                
                /**** EXTERNAL_CONTENT_URI : style URI for the "primary" external storage volume. ****/

                
                // Standard Intent action that can be sent to have the camera
                // application capture an image and return it.  
                
                Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
                
                 intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                 
                 intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                 
                startActivityForResult( intent, CAPTURE_IMAGE);
               
             /*************************** Camera Intent End ************************/
			}
		});
	}
	
	public void openGallery(int req_code){

        Intent intent = new Intent();

        intent.setType("image/*");

        intent.setAction(Intent.ACTION_GET_CONTENT);

        startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);

   }
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {



        if (resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();
            if (requestCode == SELECT_FILE_1)

            {

                selectedPath1 = getPath(getApplicationContext(), selectedImageUri);

                System.out.println("selectedPath1 : " + selectedPath1);

            }

            if (requestCode == CAPTURE_IMAGE)

            {

//                selectedPath2 = getPath(getApplicationContext(), selectedImageUri);
//
//                System.out.println("selectedPath2 : " + selectedPath2);
            	/*********** Load Captured Image And Data Start ****************/
                
                String imageId = CapturePhoto.convertImageUriToFile( imageUri,ChooseImages.this);
                

               //  Create and excecute AsyncTask to load capture image

                new LoadImagesFromSDCard().execute(""+imageId);
                
              /*********** Load Captured Image And Data End ****************/
                
           
            } else if ( resultCode == RESULT_CANCELED) {
                
                Toast.makeText(this, " Picture was not taken ", Toast.LENGTH_SHORT).show();
            } else {
                
                Toast.makeText(this, " Picture was not taken ", Toast.LENGTH_SHORT).show();
            }
            

            Log.d("Test", "Selected File paths : " + selectedPath1 + "," + selectedPath2);
            Bitmap myBitmap = BitmapFactory.decodeFile(selectedPath1);
            imageBtnImage.setImageBitmap(myBitmap);
        }

    }
	
	 public String getPath(final Context context, final Uri uri) 
	 {

		//check here to KITKAT or new version
		  final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
		 
		  // DocumentProvider
		  if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
		    
		   // ExternalStorageProvider
		   if (isExternalStorageDocument(uri)) {
		    final String docId = DocumentsContract.getDocumentId(uri);
		    final String[] split = docId.split(":");
		    final String type = split[0];
		 
		    if ("primary".equalsIgnoreCase(type)) {
		     return Environment.getExternalStorageDirectory() + "/" + split[1];
		    }
		   }
		   // DownloadsProvider
		   else if (isDownloadsDocument(uri)) {
		 
		    final String id = DocumentsContract.getDocumentId(uri);
		    final Uri contentUri = ContentUris.withAppendedId(
		      Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
		 
		    return getDataColumn(context, contentUri, null, null);
		   }
		   // MediaProvider
		   else if (isMediaDocument(uri)) {
		    final String docId = DocumentsContract.getDocumentId(uri);
		    final String[] split = docId.split(":");
		    final String type = split[0];
		 
		    Uri contentUri = null;
		    if ("image".equals(type)) {
		     contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		    } else if ("video".equals(type)) {
		     contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
		    } else if ("audio".equals(type)) {
		     contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
		    }
		 
		    final String selection = "_id=?";
		    final String[] selectionArgs = new String[] {
		      split[1]
		    };
		 
		    return getDataColumn(context, contentUri, selection, selectionArgs);
		   }
		  }
		  // MediaStore (and general)
		  else if ("content".equalsIgnoreCase(uri.getScheme())) {
		 
		   // Return the remote address
		   if (isGooglePhotosUri(uri))
		    return uri.getLastPathSegment();
		 
		   return getDataColumn(context, uri, null, null);
		  }
		  // File
		  else if ("file".equalsIgnoreCase(uri.getScheme())) {
		   return uri.getPath();
		  }
		 
		  return null;
		 }
		 
		 /**
		  * Get the value of the data column for this Uri. This is useful for
		  * MediaStore Uris, and other file-based ContentProviders.
		  *
		  * @param context The context.
		  * @param uri The Uri to query.
		  * @param selection (Optional) Filter used in the query.
		  * @param selectionArgs (Optional) Selection arguments used in the query.
		  * @return The value of the _data column, which is typically a file path.
		  */
		 public static String getDataColumn(Context context, Uri uri, String selection,
		   String[] selectionArgs) {
		 
		  Cursor cursor = null;
		  final String column = "_data";
		  final String[] projection = {
		    column
		  };
		 
		  try {
		   cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
		     null);
		   if (cursor != null && cursor.moveToFirst()) {
		    final int index = cursor.getColumnIndexOrThrow(column);
		    return cursor.getString(index);
		   }
		  } finally {
		   if (cursor != null)
		    cursor.close();
		  }
		  return null;
		 }
		 
		 /**
		  * @param uri The Uri to check.
		  * @return Whether the Uri authority is ExternalStorageProvider.
		  */
		 public static boolean isExternalStorageDocument(Uri uri) {
		  return "com.android.externalstorage.documents".equals(uri.getAuthority());
		 }
		 
		 /**
		  * @param uri The Uri to check.
		  * @return Whether the Uri authority is DownloadsProvider.
		  */
		 public static boolean isDownloadsDocument(Uri uri) {
		  return "com.android.providers.downloads.documents".equals(uri.getAuthority());
		 }
		 
		 /**
		  * @param uri The Uri to check.
		  * @return Whether the Uri authority is MediaProvider.
		  */
		 public static boolean isMediaDocument(Uri uri) {
		  return "com.android.providers.media.documents".equals(uri.getAuthority());
		 }
		 
		 /**
		  * @param uri The Uri to check.
		  * @return Whether the Uri authority is Google Photos.
		  */
		 public static boolean isGooglePhotosUri(Uri uri) {
		  return "com.google.android.apps.photos.content".equals(uri.getAuthority());
		 }
		// Class with extends AsyncTask class
	       
		    public class LoadImagesFromSDCard  extends AsyncTask<String, Void, Void> {
		           
		           private ProgressDialog Dialog = new ProgressDialog(ChooseImages.this);
		           
		           Bitmap mBitmap;
		           
		           protected void onPreExecute() {
		               /****** NOTE: You can call UI Element here. *****/
		               
		               // Progress Dialog
		               Dialog.setMessage(" Loading image from Sdcard..");
		               Dialog.show();
		           }


		           // Call after onPreExecute method
		           protected Void doInBackground(String... urls) {
		               
		               
		               Bitmap newBitmap = null;
		               Uri uri = null;       
		                   
		                   
		                   try {
		                       
		                       /**  Uri.withAppendedPath Method Description
		                       * Parameters
		                       *    baseUri  Uri to append path segment to
		                       *    pathSegment  encoded path segment to append
		                       * Returns
		                       *    a new Uri based on baseUri with the given segment appended to the path
		                       */
		                       
		                       uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + urls[0]);
		                       
		                       /**************  Decode an input stream into a bitmap. *********/
		                       bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
		                       
		                       if (bitmap != null) {
		                           
		                           /********* Creates a new bitmap, scaled from an existing bitmap. ***********/

		                           newBitmap = Bitmap.createScaledBitmap(bitmap, 170, 170, true);
		                           
		                           bitmap.recycle();
		                           
		                           if (newBitmap != null) {
		                               
		                               mBitmap = newBitmap;
		                           }
		                       }
		                   } catch (IOException e) {
		                       // Error fetching image, try to recover
		                       /********* Cancel execution of this task. **********/
		                       cancel(true);
		                   }
		               
		               return null;
		           }
		           
		           
		           protected void onPostExecute(Void unused) {
		               
		               // NOTE: You can call UI Element here.
		               
		               // Close progress dialog
		                 Dialog.dismiss();
		               
		               if(mBitmap != null)
		               {
		                 // Set Image to ImageView  
		                 
		                  imageBtnImage.setImageBitmap(mBitmap);
		               }  
		               
		           }
		           
		    }
		    
		    public int uploadFile(String sourceFileUri) {
		        String upLoadServerUri = "http://10.0.2.2:443/MakeMathWeb/index.php/api/file/";//api/upload_media_test.php";
		        String fileName = sourceFileUri;

		        HttpURLConnection conn = null;
		        DataOutputStream dos = null;  
		        String lineEnd = "\r\n";
		        String twoHyphens = "--";
		        String boundary = "*****";
		        int bytesRead, bytesAvailable, bufferSize;
		        byte[] buffer;
		        int maxBufferSize = 1 * 1024 * 1024; 
		        File sourceFile = new File(sourceFileUri); 
		        if (!sourceFile.isFile()) {
		         Log.d("Test", "Source File Does not exist");
		         return 0;
		        }
		            int serverResponseCode = 0;
					try { // open a URL connection to the Servlet
		             FileInputStream fileInputStream = new FileInputStream(sourceFile);
		             URL url = new URL(upLoadServerUri);
		             conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
		             conn.setDoInput(true); // Allow Inputs
		             conn.setDoOutput(true); // Allow Outputs
		             conn.setUseCaches(false); // Don't use a Cached Copy
		             conn.setRequestMethod("POST");
		             conn.setRequestProperty("Connection", "Keep-Alive");
		             conn.setRequestProperty("ENCTYPE", "multipart/form-data");
		             conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
		            
		             conn.setRequestProperty("uploaded_file", fileName); 
		             
		             dos = new DataOutputStream(conn.getOutputStream());
		             dos.writeBytes(twoHyphens + boundary + lineEnd); 
		             dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
		             dos.writeBytes(lineEnd);

		             bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size
		   
		             bufferSize = Math.min(bytesAvailable, maxBufferSize);
		             buffer = new byte[bufferSize];
		         
		             // read file and write it into form...
		             bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
		               
		             while (bytesRead > 0) {
		               dos.write(buffer, 0, bufferSize);
		               bytesAvailable = fileInputStream.available();
		               bufferSize = Math.min(bytesAvailable, maxBufferSize);
		               bytesRead = fileInputStream.read(buffer, 0, bufferSize);               
		              }
		   
		             Log.d("Test", "Source File Does not exist");
		             // send multipart form data necesssary after file data...
		             dos.writeBytes(lineEnd);
		             dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
		             
		             // Responses from the server (code and message)
		             serverResponseCode = conn.getResponseCode();
		             String serverResponseMessage = conn.getResponseMessage();
		              
		             Log.d("Test", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
		             if(serverResponseCode == 200){
		                 runOnUiThread(new Runnable() {
		                      public void run() {
//		                          Log.d("Test", "File Upload Completed.");
		                          Toast.makeText(ChooseImages.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
		                      }
		                  });                
		             }    
		             
		             //close the streams //
		             fileInputStream.close();
		             dos.flush();
		             dos.close();
		              
		        } catch (MalformedURLException ex) {  
//		            dialog.dismiss();  
		            ex.printStackTrace();
		            Toast.makeText(ChooseImages.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
		            Log.d("Test", "error: " + ex.getMessage(), ex);  
		        } catch (Exception e) {
//		            dialog.dismiss();  
		            e.printStackTrace();
		            Toast.makeText(ChooseImages.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
		            Log.d("Test", "Exception : " + e.getMessage(), e);  
		        }
//		        dialog.dismiss();    
					Log.d("Test", "run");  
		        return serverResponseCode;  
		       }
}
